<template>
  <div class="share-access-container">
    <div class="share-card">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>正在加载分享信息...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-state">
        <el-icon><WarningFilled /></el-icon>
        <h3>{{ error }}</h3>
        <p>请检查分享链接是否正确，或联系分享者</p>
        <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
      </div>
      
      <!-- 密码验证 -->
      <div v-else-if="needPassword && !passwordVerified" class="password-form">
        <div class="share-header">
          <el-icon><Lock /></el-icon>
          <h2>请输入访问密码</h2>
        </div>
        
        <div class="file-preview">
          <div class="file-icon">{{ getFileIcon(shareInfo.type) }}</div>
          <div class="file-info">
            <h3>{{ shareInfo.filename }}</h3>
            <p>分享者：{{ shareInfo.username }}</p>
          </div>
        </div>
        
        <el-form @submit.prevent="verifyPassword">
          <el-form-item>
            <el-input
              v-model="password"
              type="password"
              placeholder="请输入访问密码"
              size="large"
              show-password
              @keyup.enter="verifyPassword"
            />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              size="large" 
              @click="verifyPassword"
              :loading="verifying"
              style="width: 100%"
            >
              访问文件
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 文件信息展示 -->
      <div v-else class="file-content">
        <div class="share-header">
          <el-icon><Share /></el-icon>
          <h2>文件分享</h2>
        </div>
        
        <div class="file-details">
          <div class="file-icon-large">{{ getFileIcon(shareInfo.type) }}</div>
          
          <div class="file-meta">
            <h3>{{ shareInfo.filename }}</h3>
            <div class="meta-item">
              <span class="label">文件大小：</span>
              <span>{{ formatFileSize(shareInfo.size) }}</span>
            </div>
            <div class="meta-item">
              <span class="label">文件类型：</span>
              <span>{{ shareInfo.type }}</span>
            </div>
            <div class="meta-item">
              <span class="label">分享者：</span>
              <span>{{ shareInfo.username }}</span>
            </div>
            <div class="meta-item" v-if="shareInfo.expire_time">
              <span class="label">有效期至：</span>
              <span>{{ formatDate(shareInfo.expire_time) }}</span>
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <el-button 
            type="primary" 
            size="large" 
            @click="downloadFile"
            :loading="downloading"
          >
            <el-icon><Download /></el-icon>
            下载文件
          </el-button>
          
          <el-button 
            v-if="canPreview" 
            size="large" 
            @click="previewFile"
          >
            <el-icon><View /></el-icon>
            在线预览
          </el-button>
        </div>
        
        <!-- 访问统计 -->
        <div class="access-stats">
          <p>已被访问 {{ shareInfo.access_count }} 次</p>
          <p v-if="shareInfo.max_access_count">
            剩余访问次数：{{ shareInfo.max_access_count - shareInfo.access_count }}
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { accessShareApi } from '@/utils/api';
import { 
  Loading, 
  WarningFilled, 
  Lock, 
  Share, 
  Download, 
  View 
} from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

const shareCode = route.params.shareCode;
const loading = ref(true);
const error = ref('');
const shareInfo = ref(null);
const needPassword = ref(false);
const passwordVerified = ref(false);
const password = ref('');
const verifying = ref(false);
const downloading = ref(false);

const canPreview = computed(() => {
  if (!shareInfo.value) return false;
  const type = shareInfo.value.type.toLowerCase();
  return type.includes('image') || type.includes('text') || type === 'application/pdf';
});

onMounted(() => {
  loadShareInfo();
});

const loadShareInfo = async () => {
  try {
    loading.value = true;
    const response = await accessShareApi(shareCode);
    
    if (response.code === 200) {
      shareInfo.value = response.data;
      needPassword.value = !!shareInfo.value.share_password;
      if (!needPassword.value) {
        passwordVerified.value = true;
      }
    } else {
      error.value = response.msg || '分享不存在或已失效';
    }
  } catch (err) {
    console.error('加载分享信息失败:', err);
    error.value = '加载失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const verifyPassword = async () => {
  if (!password.value.trim()) {
    ElMessage.warning('请输入访问密码');
    return;
  }
  
  try {
    verifying.value = true;
    const response = await accessShareApi(shareCode, password.value);
    
    if (response.code === 200) {
      shareInfo.value = response.data;
      passwordVerified.value = true;
      ElMessage.success('密码验证成功');
    } else {
      ElMessage.error(response.msg || '密码错误');
    }
  } catch (err) {
    console.error('密码验证失败:', err);
    ElMessage.error('验证失败，请重试');
  } finally {
    verifying.value = false;
  }
};

const downloadFile = () => {
  downloading.value = true;
  // 构建下载链接
  const downloadUrl = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'}/${shareInfo.value.username}/${shareInfo.value.relativeFilePath}`;
  
  // 创建下载链接
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = shareInfo.value.filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  setTimeout(() => {
    downloading.value = false;
  }, 1000);
  
  ElMessage.success('开始下载');
};

const previewFile = () => {
  const previewUrl = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'}/${shareInfo.value.username}/${shareInfo.value.relativeFilePath}`;
  window.open(previewUrl, '_blank');
};

const getFileIcon = (type) => {
  if (!type) return '📄';
  
  if (type.includes('image')) return '🖼️';
  if (type.includes('video')) return '🎬';
  if (type.includes('audio')) return '🎵';
  if (type.includes('pdf')) return '📕';
  if (type.includes('word') || type.includes('doc')) return '📘';
  if (type.includes('excel') || type.includes('sheet')) return '📗';
  if (type.includes('powerpoint') || type.includes('presentation')) return '📙';
  if (type.includes('zip') || type.includes('rar')) return '📦';
  if (type.includes('text')) return '📝';
  
  return '📄';
};

const formatFileSize = (sizeInMB) => {
  if (sizeInMB < 1) {
    return `${Math.round(sizeInMB * 1024)} KB`;
  } else if (sizeInMB < 1024) {
    return `${sizeInMB.toFixed(1)} MB`;
  } else {
    return `${(sizeInMB / 1024).toFixed(1)} GB`;
  }
};

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN');
};
</script>

<style lang="less" scoped>
.share-access-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.share-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  max-width: 500px;
  width: 100%;
  overflow: hidden;
}

.loading-state,
.error-state {
  text-align: center;
  padding: 60px 40px;
  
  .el-icon {
    font-size: 48px;
    color: #909399;
    margin-bottom: 16px;
  }
  
  h3 {
    color: #303133;
    margin-bottom: 8px;
  }
  
  p {
    color: #606266;
    margin-bottom: 20px;
  }
}

.password-form,
.file-content {
  padding: 40px;
}

.share-header {
  text-align: center;
  margin-bottom: 30px;
  
  .el-icon {
    font-size: 32px;
    color: #409eff;
    margin-bottom: 8px;
  }
  
  h2 {
    color: #303133;
    margin: 0;
  }
}

.file-preview {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 30px;
  
  .file-icon {
    font-size: 32px;
    margin-right: 15px;
  }
  
  .file-info {
    h3 {
      margin: 0 0 5px 0;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }
}

.file-details {
  text-align: center;
  margin-bottom: 30px;
  
  .file-icon-large {
    font-size: 64px;
    margin-bottom: 20px;
  }
  
  h3 {
    color: #303133;
    margin-bottom: 20px;
    word-break: break-all;
  }
  
  .meta-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    
    .label {
      color: #606266;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  
  .el-button {
    flex: 1;
  }
}

.access-stats {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  
  p {
    margin: 4px 0;
    color: #909399;
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .share-access-container {
    padding: 10px;
  }
  
  .password-form,
  .file-content {
    padding: 20px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>
